package com.lindroid.androiduilearning.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.lindroid.androiduilearning.R;

import java.util.List;

/**
 * @author Lin
 * @date 2018/3/9
 * @function
 */

public class BaseActivity extends AppCompatActivity {
    public Context context;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;

    }

    public void initBlueToolBar(String title,boolean isShowBack){
        View toolBarView = this.getWindow().getDecorView();
        Toolbar toolbar = toolBarView.findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(isShowBack);
            //将ActionBar的标题禁掉
            actionBar.setDisplayShowTitleEnabled(false);
        }

        toolbar.setTitle(title);

        if (isShowBack){
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    /**
     * @param from:当前显示的Fragment
     * @param to:要跳转到的Fragment
     */
    public BaseFragment switchFragment(@IdRes int rootLayout, BaseFragment from, BaseFragment to) {
        if (from != to) {
            //如需要跳转的Fragment跟当前的Fragment相同，则无需切换
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            if (to != null && !to.isAdded()) {
                //没有添加
                //隐藏from
                if (from != null) {
                    ft.hide(from);
                }
                //添加to
                ft.add(rootLayout, to).commit();
            } else {//to已经被添加
                // from隐藏
                if (from != null) {
                    ft.hide(from);
                }
                //显示to
                if (to != null) {
                    //to已经添加过了，只需show即可
                    ft.show(to).commit();
                }
            }
        }

        return to;
    }

    public BaseFragment getFragment(List<BaseFragment> fragmentList, int position) {
        return fragmentList.get(position);
    }

}
